package com.cus.tom.transfer.utils;

import static com.cus.tom.transfer.utils.ComUtility.close;

import android.content.ContentProviderOperation;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.OperationApplicationException;
import android.net.Uri;
import android.os.Build;
import android.os.Looper;
import android.os.RemoteException;
import android.provider.CallLog;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.CommonDataKinds.StructuredName;
import android.provider.ContactsContract.Contacts.Data;
import android.provider.Telephony;

import androidx.core.content.FileProvider;
import androidx.fragment.app.Fragment;

import com.cus.tom.transfer.App;
import com.cus.tom.transfer.BuildConfig;
import com.cus.tom.transfer.bean.Contractor;
import com.cus.tom.transfer.bean.MediaData;
import com.cus.tom.transfer.bean.PhoneCall;
import com.cus.tom.transfer.bean.Sms;
import com.cus.tom.transfer.frag.LoadingDlg;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.plata.base.utils.WeakHandler;

import java.io.File;
import java.io.FileInputStream;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

public class Write {

    WeakHandler h = new WeakHandler(Looper.getMainLooper());

    public void addContract(MediaData data, LoadingDlg dlg) {
        FileInputStream fin = null;
        try {
            File f = new File(data.getPath());
            byte[] b = new byte[(int) f.length()];
            fin = new FileInputStream(f);
            fin.read(b);
            String s = new String(b);
            Type type = new TypeToken<List<Contractor>>() {
            }.getType();
            List<Contractor> list = new Gson().fromJson(s, type);
            int i = 0;
            int total = list.size();
            for (Contractor item : list) {
                doAddContact(App.getApp(), item);
                int j = ++i;
                h.post(() -> {
                    dlg.setMsg("已导入" + j + "条记录，共" + total + "条");
                });
            }
        } catch (Throwable e) {
            e.printStackTrace();
        } finally {
            close(fin);
        }
    }

    /**
     * 检查是否是英文名称
     *
     * @param name
     * @return
     */
    private boolean checkEnglishName(String name) {
        char[] nameChars = name.toCharArray();
        for (int i = 0; i < nameChars.length; i++) {
            if ((nameChars[i] >= 'a' && nameChars[i] <= 'z')
                    || (nameChars[i] >= 'A' && nameChars[i] <= 'Z')) {
                continue;
            }
            return false;
        }
        return true;
    }

    /**
     * 向数据库表插入联系人信息
     *
     * @param context
     * @param contactInfo
     * @return
     */
    private boolean doAddContact(Context context, Contractor contactInfo) {
        try {
            ContentValues contentValues = new ContentValues();
            Uri uri = context.getContentResolver().insert(
                    ContactsContract.RawContacts.CONTENT_URI, contentValues);
            long rowId = ContentUris.parseId(uri);

            String name = contactInfo.name;
            String mobileNum = contactInfo.number;

            // 插入姓名
            if (name != null) {
                contentValues.clear();
                contentValues.put(Data.RAW_CONTACT_ID, rowId);
                contentValues.put(Data.MIMETYPE,
                        StructuredName.CONTENT_ITEM_TYPE);
                int index = name.length() / 2;
                String displayName = name;
                String givenName = null;
                String familyName = null;
                // 检查是否是英文名称
                if (checkEnglishName(displayName) == false) {
                    givenName = name.substring(index);
                    familyName = name.substring(0, index);
                } else {
                    givenName = familyName = displayName;
                }
                contentValues.put(StructuredName.DISPLAY_NAME, displayName);
                contentValues.put(StructuredName.GIVEN_NAME, givenName);
                contentValues.put(StructuredName.FAMILY_NAME, familyName);
                context.getContentResolver().insert(
                        ContactsContract.Data.CONTENT_URI, contentValues);
            }

            if (mobileNum != null) {
                // 插入手机电话
                contentValues.clear();
                contentValues.put(Data.RAW_CONTACT_ID, rowId);
                contentValues.put(Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE);
                contentValues.put(Phone.NUMBER, mobileNum);
                contentValues.put(Phone.TYPE, Phone.TYPE_MOBILE);
                context.getContentResolver().insert(
                        ContactsContract.Data.CONTENT_URI, contentValues);
            }

//            if (homeNum != null) {
//                // 插入家庭号码
//                contentValues.clear();
//                contentValues.put(Data.RAW_CONTACT_ID, rowId);
//                contentValues.put(Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE);
//                contentValues.put(Phone.NUMBER, homeNum);
//                contentValues.put(Phone.TYPE, Phone.TYPE_HOME);
//                context.getContentResolver().insert(
//                        ContactsContract.Data.CONTENT_URI, contentValues);
//            }
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    public void addSms(MediaData data, LoadingDlg dlg) {
        FileInputStream fin = null;
        try {
            File f = new File(data.getPath());
            byte[] b = new byte[(int) f.length()];
            fin = new FileInputStream(f);
            fin.read(b);
            String s = new String(b);
            Type type = new TypeToken<List<Sms>>() {
            }.getType();
            List<Sms> list = new Gson().fromJson(s, type);
            int i = 0;
            int total = list.size();
            for (Sms item : list) {
                doAddSms(App.getApp(), item);
                int j = ++i;
                h.post(() -> {
                    dlg.setMsg("已导入" + j + "条记录，共" + total + "条");
                });
                if (BuildConfig.DEBUG && j >= 1) {
                    break;
                }
            }
        } catch (Throwable e) {
            e.printStackTrace();
        } finally {
            close(fin);
        }
    }

    private boolean doAddSms(Context context, Sms info) {
        try {
            ContentValues contentValues = new ContentValues();

            contentValues.clear();
            contentValues.put(Telephony.Sms.TYPE, info.type);
            contentValues.put(Telephony.Sms.DATE_SENT, info.dateSent);
            contentValues.put(Telephony.Sms.DATE, info.time);
            contentValues.put(Telephony.Sms.READ, info.read);
            contentValues.put(Telephony.Sms.SEEN, info.seen);
            contentValues.put(Telephony.Sms.BODY, info.content);
//            contentValues.put(Telephony.Sms._ID, rowId);
            contentValues.put(Telephony.Sms.STATUS, info.status);
            contentValues.put(Telephony.Sms.PERSON, info.person);
            contentValues.put(Telephony.Sms.ADDRESS, info.phone);

            Uri uri = context.getContentResolver().insert(
                    Telephony.Sms.CONTENT_URI, contentValues);
            long rowId = ContentUris.parseId(uri);
            System.currentTimeMillis();
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    public static void install(Fragment fragment, String newApkPath, int code) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        File apkFile = new File(newApkPath);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            Uri uri = FileProvider.getUriForFile(App.getApp(), BuildConfig.APPLICATION_ID, apkFile);
            intent.setDataAndType(uri, "application/vnd.android.package-archive");
        } else {
            intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
        }
        fragment.startActivityForResult(intent, code);
    }

    public void addPhoneCall(MediaData data, LoadingDlg dlg) {
        FileInputStream fin = null;
        try {
            File f = new File(data.getPath());
            byte[] b = new byte[(int) f.length()];
            fin = new FileInputStream(f);
            fin.read(b);
            String s = new String(b);
            Type type = new TypeToken<List<PhoneCall>>() {
            }.getType();
            List<PhoneCall> list = new Gson().fromJson(s, type);
            batchAddCallLogs(list, dlg);
        } catch (Throwable e) {
            e.printStackTrace();
        } finally {
            close(fin);
        }
    }

    private void batchAddCallLogs(List<PhoneCall> list, LoadingDlg dlg)
            throws RemoteException, OperationApplicationException {
        try {
            ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
            ContentValues values = new ContentValues();

            for (PhoneCall calllog : list) {
                values.clear();
                values.put(CallLog.Calls.NUMBER, calllog.number);
                values.put(CallLog.Calls.TYPE, calllog.type);
                values.put(CallLog.Calls.DATE, calllog.date);
                values.put(CallLog.Calls.DURATION, calllog.duration);
                values.put(CallLog.Calls.NEW, calllog.turnOn);
                values.put(CallLog.Calls.CACHED_NAME, calllog.name);

                ops.add(ContentProviderOperation
                        .newInsert(CallLog.Calls.CONTENT_URI).withValues(values)
                        .withYieldAllowed(true).build());
            }
            if (ops != null) {
                App.getApp().getContentResolver().applyBatch(CallLog.AUTHORITY, ops);
            }
            return;
        } catch (Throwable e) {
            e.printStackTrace();
        }
        ContentValues values = new ContentValues();

        int i = 0;
        int total = list.size();
        for (PhoneCall calllog : list) {
            values.clear();
            values.put(CallLog.Calls.NUMBER, calllog.number);
            values.put(CallLog.Calls.TYPE, calllog.type);
            values.put(CallLog.Calls.DATE, calllog.date);
            values.put(CallLog.Calls.DURATION, calllog.duration);
            values.put(CallLog.Calls.NEW, calllog.turnOn);
            values.put(CallLog.Calls.CACHED_NAME, calllog.name);

            Uri uri = App.getApp().getContentResolver().insert(
                    CallLog.Calls.CONTENT_URI, values);
            long rowId = ContentUris.parseId(uri);

            int j = ++i;
            h.post(() -> {
                dlg.setMsg("已导入" + j + "条记录，共" + total + "条");
            });
            if (j >= 1) {
                break;
            }
        }
    }
}
